package com.aizu.utils;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.log4j.Logger;

/**
 * 短信工具类
 */
public class HttpUtils {

	private static Logger logger = Logger.getLogger(HttpUtils.class);

	private static MultiThreadedHttpConnectionManager connectionManager = null;

	private static int connectionTimeOut = 25000;

	private static int socketTimeOut = 25000;

	private static int maxConnectionPerHost = 20;//HOST并发数

	private static int maxTotalConnections = 50;//客户端总并发数

	private static HttpClient client;

	static {
		connectionManager = new MultiThreadedHttpConnectionManager();
		connectionManager.getParams().setConnectionTimeout(connectionTimeOut);
		connectionManager.getParams().setSoTimeout(socketTimeOut);
		connectionManager.getParams().setDefaultMaxConnectionsPerHost(maxConnectionPerHost);
		connectionManager.getParams().setMaxTotalConnections(maxTotalConnections);
		client = new HttpClient(connectionManager);
	}

	/**
	 * 发送短信
	 * 
	 * @param phone
	 *            接收者手机号
	 * @param content
	 *            发送内容
	 * @return
	 * @throws IOException
	 */
	public static String post(String url, Map<String, String> params) throws IOException {
//		return "{\"result\":{\"flag\":\"0\",\"msg\":\"模拟成功报文\"}}";
		String response = null;
		PostMethod postMethod = new PostMethod(url);
		postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
		// 将表单的值放入postMethod中
		Set<String> keySet = params.keySet();
		for (String key : keySet) {
			String value = params.get(key);
			postMethod.addParameter(key, value);
		}
		// 执行postMethod
		try {
			logger.info("url: " + url);
			logger.info("data: " + params);
			int statusCode = client.executeMethod(postMethod);
			if (statusCode == HttpStatus.SC_OK) {
				response = postMethod.getResponseBodyAsString();
			} else {
				logger.error("响应状态码 = " + postMethod.getStatusCode());
				response = postMethod.getStatusCode() + "";
			}
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (postMethod != null) {
				postMethod.releaseConnection();
				postMethod = null;
			}
		}
		return response;
	}

}
